package com.mes.check.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessResourceFailureException;

import com.mes.check.dao.iface.ICertificateDao;
import com.mes.check.domain.Certificate;
import com.mes.common.dao.BasicDao;

public class CertificateDao extends BasicDao<Certificate> implements ICertificateDao {
	private static final Log log = LogFactory.getLog(CertificateDao.class);


	@Override
	public List<Certificate> getCertificatesById(String certificateId)
			throws Exception {
		List list=null;
		try {
			log.info("++++++++++++++++++++++++++++++++++++getCertificatesById");
			Session session=this.getSession();
			StringBuilder hql=new StringBuilder();
			hql.append(" from " + CertificateDao.class.getName() + " where ");
			hql.append( " certificateId=? ");
			Query query = session.createQuery(hql.toString());
			query.setString(0, certificateId);

			list = query.list();
		} catch (DataAccessResourceFailureException e) {
			e.printStackTrace();
		} catch (HibernateException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Certificate getEffectiveCertificateById(String certificateId)
			throws Exception {
		Certificate certificate=null;
		try {
			log.info("++++++++++++++++++++++++++++++++++++getEffectiveCertificateById");
			Session session=this.getSession();
			StringBuilder hql=new StringBuilder();
			
			Criteria crit = session.createCriteria(Certificate.class);
			crit.add(Restrictions.eq("certificateId", certificateId));
			crit.add(Restrictions.eq("certificateState", Certificate.CERTIFICATE_STATE_EFFECTIVE));
			crit.setMaxResults(1);

			certificate = (Certificate)crit.uniqueResult();			

		} catch (DataAccessResourceFailureException e) {
			e.printStackTrace();
		} catch (HibernateException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		return certificate;
	}
}
